package com.bw.module_service.websocket

import org.java_websocket.client.WebSocketClient
import org.java_websocket.handshake.ServerHandshake
import java.net.URI

class WebSocketManager private constructor() {
    companion object {
        private const val WEBSOCKET_URL = "ws://your-server.com/api/announcements"
        val instance by lazy { WebSocketManager() }
    }

    private var webSocketClient: WebSocketClient? = null
    private var listeners: MutableList<WebSocketListener> = mutableListOf()

    interface WebSocketListener {
        fun onConnected()
        fun onDisconnected()
        fun onMessageReceived(message: String)
        fun onError(error: Exception)
    }

    fun addListener(listener: WebSocketListener) {
        listeners.add(listener)
    }

    fun removeListener(listener: WebSocketListener) {
        listeners.remove(listener)
    }

    fun connect() {
        if (webSocketClient != null && webSocketClient!!.isOpen) {
            return
        }

        val uri = URI(WEBSOCKET_URL)
        webSocketClient = object : WebSocketClient(uri) {
            override fun onOpen(handshakedata: ServerHandshake?) {
                listeners.forEach { it.onConnected() }
            }

            override fun onMessage(message: String?) {
                message?.let { listeners.forEach { listener -> listener.onMessageReceived(it) } }
            }

            override fun onClose(code: Int, reason: String?, remote: Boolean) {
                listeners.forEach { it.onDisconnected() }
            }

            override fun onError(ex: Exception?) {
                ex?.let { listeners.forEach { listener -> listener.onError(it) } }
            }
        }

        webSocketClient?.connect()
    }

    fun disconnect() {
        webSocketClient?.close()
        webSocketClient = null
    }

    fun sendAnnouncement(title: String, content: String) {
        val message = createAnnouncementMessage(title, content)
        webSocketClient?.send(message)
    }

    private fun createAnnouncementMessage(title: String, content: String): String {
        // 根据API要求构建JSON消息
        return """
            {
                "action": "publish_announcement",
                "data": {
                    "title": "$title",
                    "content": "$content",
                    "publishTime": "${System.currentTimeMillis()}"
                }
            }
        """.trimIndent()
    }
}